package cool.mtc.minghe.service.manager.sys.user.impl;

import cool.mtc.minghe.data.model.sys.user.dto.UserDetailDTO;
import cool.mtc.minghe.data.model.sys.user.dto.UserOrgDTO;
import cool.mtc.minghe.service.manager.BaseManagerImpl;
import cool.mtc.minghe.service.manager.sys.user.UserManager;
import cool.mtc.minghe.service.mapper.security.SecurityMapper;
import cool.mtc.minghe.service.mapper.sys.user.UserMapper;
import cool.mtc.minghe.service.mapper.sys.user.UserOrgRoleMapper;
import cool.mtc.security.data.model.UserDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 明河
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserManagerImpl extends BaseManagerImpl implements UserManager {
    private final UserMapper userMapper;
    private final UserOrgRoleMapper userOrgRoleMapper;
    private final SecurityMapper securityMapper;

    @Override
    @Cacheable(value = "user_details", key = "'user_id_' + #userId + ':org_id_' + #orgId + ':auth_type_' + #authType", unless = "null == #result")
    public UserDetails getUserDetailsByUserIdAndOrgIdAndAuthType(long userId, long orgId, String authType) {
        UserDetails user = securityMapper.getByUserIdAndAuthType(userId, authType);
        if (null == user) {
            return null;
        }
        user.setOrgId(orgId);
        // 权限字符列表
        List<String> permissionList = userOrgRoleMapper.listPermissionByUserIdAndOrgId(userId, orgId);
        user.setPermissionList(permissionList);
        return user;
    }

    @Override
    @Cacheable(value = "user", key = "'id_' + #userId", unless = "null == #result ")
    public UserDetailDTO getUserDetailByUserIdAndOrgId(long userId, long orgId) {
        UserDetailDTO user = userMapper.getUserDetailById(userId);
        if (null == user) {
            return null;
        }
        // 权限字符列表
        List<String> permissionList = userOrgRoleMapper.listPermissionByUserIdAndOrgId(userId, orgId);
        user.setPermissionList(permissionList);
        // 单位列表
        List<UserOrgDTO> orgList = userOrgRoleMapper.listOrgByUserId(userId);
        user.setOrgList(orgList);
        orgList.stream()
                .filter(item -> item.getOrgId() == orgId)
                .findFirst()
                .ifPresent(item -> {
                    user.setOrgId(item.getOrgId());
                    user.setOrgName(item.getOrgName());
                });
        return user;
    }

    @Override
    @Cacheable(value = "user_permission", key = "'user_id_' + #userId + ':org_id_' + #orgId", unless = "null == #result ")
    public List<String> listPermissionByUserIdAndOrgId(long userId, Long orgId) {
        return userOrgRoleMapper.listPermissionByUserIdAndOrgId(userId, orgId);
    }
}
